package com.hdjk.view.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.hdjk.view.BuildConfig;

public class HttpUtil {

	public static String httpRequest(String path) {
		URL url;
		String http = "";
		String params = "";
		int index = path.indexOf("?");
		if (index == -1) {
			http = path;
		} else {
			http = path.substring(0, index);
			params = path.substring(index + 1);
		}

		try {
			url = new URL(http);

			URLConnection conn = url.openConnection();

			conn.setDoOutput(true);
			conn.setDoInput(true);

			PrintWriter out = new PrintWriter(conn.getOutputStream());
			out.print(params);
			out.flush();

			InputStream inputStream = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(inputStream, "utf8");
			StringBuffer sb = new StringBuffer();
			BufferedReader in = new BufferedReader(isr);
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				sb.append(inputLine);
				sb.append("\n");
			}
			String result = sb.toString();

			return result;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String connectByGet(String path, Map<String, String> params, int timeout) {
		BufferedReader in = null;
		StringBuffer sb = null;
		String result = "";
		OutputStream outputStream = null;
		try {
			String dataStr = "";
			if (params != null || !"".equals(params)) {
				dataStr = getRequestData(params, "utf-8").toString();// 获得请求体
			}
			
			URL url = new URL(path + "?" + dataStr);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setConnectTimeout(timeout);// 设置连接超时时间
			httpURLConnection.setReadTimeout(timeout);
			httpURLConnection.setRequestMethod("GET");// 设置以Post方式提交数据
			httpURLConnection.setUseCaches(false); // 使用Post方式不能使用缓存

			// 设置自定义的参数
			httpURLConnection.setRequestProperty("version_code", BuildConfig.VERSION_NAME);
			httpURLConnection.setRequestProperty("source_type", BuildConfig.yfhdcf_CHANNEL_VALUE);
			
			httpURLConnection.connect();
			
			int response = httpURLConnection.getResponseCode(); // 获得服务器的响应码
			if (response == HttpURLConnection.HTTP_OK) {
				// InputStream inptStream = httpURLConnection.getInputStream();
				// return dealResponseResult(inptStream); //处理服务器的响应结果

				// 定义BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(
						httpURLConnection.getInputStream(), "utf-8"));

				// 开始读取数据流
				String line;
				sb = new StringBuffer();
				while ((line = in.readLine()) != null) {
					sb.append(line);
				}

				// Get the result
				result = sb.toString();
				//Log.i("result=",result);
				//判断返回的数据是不是html类型的，如果是直接返回空字符串
				if(!TextUtils.isEmpty(result)&&(result.startsWith("<html>")||result.startsWith("<HTML>"))){
					return "";
				}
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

	public static String connectByPostJson(String path, String params, int timeout) {
		try {
			byte[] data = null;
			if (params != null || !"".equals(params)) {
				data = params.getBytes();// 获得请求体
			} else {
				data = new byte[0];
			}
			
			return connectByPost(path, data, timeout, "application/json");
		} catch (Exception e) {
		}
		return null;
	}
	
	public static String connectByPostKeyValue(String path, Map<String, String> params, int timeout) {
		try {
			byte[] data = null;
			if (params != null || !"".equals(params)) {
				data = getRequestData(params, "utf-8").toString().getBytes();// 获得请求体
			} else {
				data = new byte[0];
			}
			
			return connectByPost(path, data, timeout, "application/x-www-form-urlencoded");
		} catch (Exception e) {
		}
		return null;
	}
	
	private static String connectByPost(String path, byte[] data, int timeout, String contentType) {
		BufferedReader in = null;
		StringBuffer sb = null;
		String result = "";
		OutputStream outputStream = null;
		try {
			URL url = new URL(path);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setConnectTimeout(timeout);// 设置连接超时时间
			httpURLConnection.setReadTimeout(timeout);
			httpURLConnection.setDoInput(true); // 打开输入流，以便从服务器获取数据
			httpURLConnection.setDoOutput(true); // 打开输出流，以便向服务器提交数据
			httpURLConnection.setRequestMethod("POST");// 设置以Post方式提交数据
			httpURLConnection.setUseCaches(false); // 使用Post方式不能使用缓存
			httpURLConnection.setChunkedStreamingMode(0);//可以改变请求模式，设置了ChunkedStreamingMode后，不再等待OutputStream关闭后生成完整的http request一次过发送，而是先发送 http request头，正文内容则是网路流的方式实时传送到服务器
			// 设置请求体的类型是文本类型
			httpURLConnection.setRequestProperty("Content-Type", contentType);
			
			// 设置请求体的长度
			httpURLConnection.setRequestProperty("Content-Length",
					String.valueOf(data.length));

			// 设置自定义的参数
			httpURLConnection.setRequestProperty("version_code", BuildConfig.VERSION_NAME);
			httpURLConnection.setRequestProperty("source_type", BuildConfig.yfhdcf_CHANNEL_VALUE);

			// 获得输出流，向服务器写入数据
			outputStream = httpURLConnection.getOutputStream();
			outputStream.write(data);
			int response = httpURLConnection.getResponseCode(); // 获得服务器的响应码
			if (response == HttpURLConnection.HTTP_OK) {
				// InputStream inptStream = httpURLConnection.getInputStream();
				// return dealResponseResult(inptStream); //处理服务器的响应结果

				// 定义BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(
						httpURLConnection.getInputStream(), "utf-8"));

				// 开始读取数据流
				String line;
				sb = new StringBuffer();
				while ((line = in.readLine()) != null) {
					sb.append(line);
				}

				// Get the result
				result = sb.toString();
				//Log.i("result=",result);
				//判断返回的数据是不是html类型的，如果是直接返回空字符串
				if(!TextUtils.isEmpty(result)&&(result.startsWith("<html>")||result.startsWith("<HTML>"))){
					return "";
				}
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}
	
	public static StringBuffer getRequestData(Map<String, String> params,
			String encode) {
		StringBuffer stringBuffer = new StringBuffer();
		try {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				stringBuffer.append(entry.getKey()).append("=")
						.append(URLEncoder.encode(entry.getValue(), encode))
						.append("&");
			}
			stringBuffer.deleteCharAt(stringBuffer.length() - 1); // 删除最后的一个"&"
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stringBuffer;
	}

	/**
	 * 下载文件
	 * @param downloadUrl
     * @param handler
     */
	public static void downloadFile(String downloadUrl, File saveFile, Handler handler){
		Message msg = new Message();
		msg.what= 0;

		int downloadCount = 0;
		long totalSize = 0;
		int updateTotalSize = 0;

		HttpURLConnection httpConnection = null;
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			URL url = new URL(downloadUrl);
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
			httpConnection.setConnectTimeout(10000);
			httpConnection.setReadTimeout(20000);
			updateTotalSize = httpConnection.getContentLength();
			if (httpConnection.getResponseCode() == 404) {
				if(handler!=null){
					msg.obj = "404 error";
					handler.sendMessage(msg);
				}
				return;
			}
			is = httpConnection.getInputStream();
			fos = new FileOutputStream(saveFile, false);
			byte buffer[] = new byte[4096];
			int readsize = 0;
			while ((readsize = is.read(buffer)) > 0) {
				fos.write(buffer, 0, readsize);
				totalSize += readsize;
				// 为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
				if ((downloadCount == 0) || (int) (totalSize * 100 / updateTotalSize) - 10 > downloadCount) {
					downloadCount += 10;
					int curProgress= (int) (totalSize * 100 / updateTotalSize);

					if(handler != null){
						msg.what = 1;
						msg.obj = curProgress + "";
						handler.sendMessage(msg);
					}
				}
			}
			msg.what =2;
			msg.obj = "success";
			handler.sendMessage(msg);
		} catch (IOException e) {
			e.printStackTrace();
			if(handler!=null){
				msg.obj = e.toString();
				handler.sendMessage(msg);
			}
		} finally {
			if (httpConnection != null) {
				httpConnection.disconnect();
			}
			try {
				if (is != null) {
					is.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
